package ar.com.angrymachine.gameui;

import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;

public class MessageBox extends Widget implements ButtonWidget.ButtonListener
{
	private String message;
	private ButtonWidget okButton;
	private MessageBoxListener listener;
	
	public interface MessageBoxListener
	{
		void onMessageBoxClosed(String buttonLabel);
	}
	
	public MessageBox(Widget parent, MessageBoxListener listener, String message, String buttonLabel)
	{
		super(parent, new Rectangle());
		// center the box
		int width = (parent.getWidth() * 2)/3;
		int fontHeight = Utils.stringSize(GameCanvas.screen.getCurrentGraphics(), message).y; 
		int height = fontHeight * 10;
		Point center = Utils.getCenterInRect(new Point(width,height), parent.getRelativeRect());
		construct(listener, new Rectangle(center.x, center.y, width, height), message, buttonLabel);
	}
	
	public MessageBox(Widget parent, MessageBoxListener listener, Rectangle area, String message, String buttonLabel)
	{
		super(parent, area);
		construct(listener, area, message, buttonLabel);
	}
	
	private void construct(MessageBoxListener listener, Rectangle area, String message, String buttonLabel)
	{
		this.listener = listener;
		setRelativeRect(area);
		this.message = message;
		// create button
		Point stringSize = Utils.stringSize(GameCanvas.screen.getCurrentGraphics(), buttonLabel);
		int buttonWidth = stringSize.x*2;
		int buttonHeight = stringSize.y*2;
		Point center = Utils.getCenterInRect(new Point(buttonWidth,buttonHeight), new Rectangle(0,0,area.width,area.height));
		okButton = new ButtonWidget(this, new Rectangle(center.x,area.height - buttonHeight - 10,buttonWidth,buttonHeight), buttonLabel, this);
	}
	
	public void paint(Graphics g)
    {
    	// paint background
		g.setColor(GameCanvas.screen.theme.buttonFillColor());
		g.fillRect(0, 0, getWidth(), getHeight());
		// border
		g.setColor(GameCanvas.screen.theme.buttonBorderColor());
    	g.drawRect(0, 0, getWidth(), getHeight());
    	// message
    	Point textSize = Utils.stringSize(g, message);
    	int textX = (getWidth() - textSize.x)/2;
        g.setFont(GameCanvas.screen.theme.getDefaultSmallFont());
    	Utils.drawString(g, message, textX, 10);
    }

	public void onPress(ButtonWidget widget)
	{
		if(widget == okButton)
		{
			listener.onMessageBoxClosed(widget.getLabel());
			close();
		}
	}	
}
